package com.grgbanking.it.common.util.poi;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.commons.collections.map.CaseInsensitiveMap;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Component;

import com.grgbanking.it.common.entity.GridExportParam;
import com.grgbanking.it.common.util.Converter;

/**
 * POI创建者
 * 
 * POICreator
 * 
 * @author 潘广伟
 * @Email p_3er@qq.com
 * @Date 2015-3-5 下午4:10:12
 * 
 * @version 1.0.0
 *
 */
@Component
public class POICreator {
	/**
	 * 获取一个Shell组装者
	 * creatteContrutctor
	 * 
	 * @param sheet
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public POIShellContructor creatteContrutctor(HSSFSheet sheet){
		return new POIShellContructor(sheet);
	}
	
	/**
	 * 创建间sheet的Book
	 * createOneSheetBook
	 * 
	 * @param exportParams
	 * @param data
	 * @return 
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public HSSFWorkbook createOneSheetBook(String title,List data,String exportParams) throws Exception{
		HSSFWorkbook workbook = new HSSFWorkbook();
		
		GridExportParam[] params = convert(exportParams);
		
        String[] headers = new String[params.length];
        for(int i=0; i < params.length; i++){
        	headers[i] = params[i].getTitle();
        }
        POIShellContructor contructor = this.creatteContrutctor(workbook.createSheet(title));
		// 设置表格默认列宽度为15个字节
		contructor.setDefaultColumnWidth(10);
		
		contructor.setHeader(0, headers); 
		
		for (int i = 0; i < data.size(); i++) {
			HSSFRow row = contructor.createRow(i+1);
			for (int j = 0; j < params.length; j++) {
				Object obj = data.get(i);
				String name = params[j].getName();
				Object value = "";
				if(obj instanceof Map){
					CaseInsensitiveMap map = new CaseInsensitiveMap((Map) obj);
					value = map.get(name.toUpperCase());
				}else{
					value = Converter.getFieldValue(obj, name);
				}
				
				contructor.setCellText(row, j,value== null ? "" : value+"");
			}
		}
		
		return workbook;
	}
	
	public GridExportParam[] convert(String exportParams){
		JSONArray jsArray = JSONArray.fromObject(exportParams);
		GridExportParam[] params = (GridExportParam[]) JSONArray
				.toArray(jsArray, GridExportParam.class);
		
		return params;
	}
	
}
